package service

import (
	"plugin"
	"runtime"

	"gitee.com/xuesongtao/protoc-go-valid/log"
)

type symCryptFunc func(string) (string, error)

var (
	// 解码
	SymDecrypt1Func symCryptFunc
	SymDecrypt2Func symCryptFunc

	// 编码
	SymEncrypt1Func symCryptFunc
	SymEncrypt2Func symCryptFunc
)

func init() {
	if runtime.GOOS == "linux" {
		initSymLinux()
	} else {
		initSymNotLinux()
	}
}

// 加密和解密
func initSymLinux() {
	log.Info("init linux sys")
	p, err := plugin.Open("/usr/lib64/encrypt.so")
	if err != nil {
		panic(err)
	}

	symEncrypt1, err := p.Lookup("Encrypt1")
	if err != nil {
		panic(err)
	}
	SymEncrypt1Func = symEncrypt1.(func(string) (string, error))

	symDecrypt1, err := p.Lookup("Decrypt1")
	if err != nil {
		panic(err)
	}
	SymDecrypt1Func = symDecrypt1.(func(string) (string, error))

	symEncrypt2, err := p.Lookup("Encrypt2")
	if err != nil {
		panic(err)
	}
	SymEncrypt2Func = symEncrypt2.(func(string) (string, error))

	symDecrypt2, err := p.Lookup("Decrypt2")
	if err != nil {
		panic(err)
	}
	SymDecrypt2Func = symDecrypt2.(func(string) (string, error))
}

func initSymNotLinux() {
	log.Info("init not linux sys")
	emptyFunc := func(val string) (string, error) {
		return val, nil
	}
	SymEncrypt1Func = emptyFunc // 登录加解密方法
	SymDecrypt1Func = emptyFunc
	SymEncrypt2Func = emptyFunc // 普通加解密
	SymDecrypt2Func = emptyFunc
}
